package com.xiaolun;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author 硕鼠
 * @Date 2020/6/1 15:43
 * @Version 1.0
 * @Description 文件说明
 */
public class TestLock {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();

        new Thread(testLock2).start();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
    }
}

//买票的例子
class TestLock2 implements Runnable{

    int tickNums = 10;

    //定义lock锁
    private final ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while(true){
            lock.lock(); //显式加锁
            try{  //保证线程安全的代码
                if (tickNums > 0){
                    System.out.println(tickNums --);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    break;
                }
            }finally {
                lock.unlock(); //显式解锁
            }
        }
    }
}